package com.xunlai.infra.permission.business.service.impl;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.xunlai.infra.permission.business.config.WxPayConfig;
import com.xunlai.infra.permission.business.dao.entity.Order;
import com.xunlai.infra.permission.business.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author liang
 * @date 9/8/23 7:33 PM
 */
@Service
public class WxPayServiceImpl implements WxPayService {

    private WxPayConfig wxPayConfig;
    private Config payConfig;

    @Override
    public String nativePay(Order order) {
        NativePayService service = new NativePayService.Builder().config(payConfig).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        BigDecimal totalPayAmount = order.getTotalPayAmount();
        BigDecimal multiply = totalPayAmount.multiply(new BigDecimal("100"));
        Amount amount = new Amount();
        amount.setTotal(multiply.intValue());
        request.setAmount(amount);
        request.setAppid(wxPayConfig.appid());
        request.setMchid(wxPayConfig.merchantId());
        request.setDescription("北京逸客网会员");
        request.setNotifyUrl("http://123.57.183.223/travel/manage/order/wxpay/notify");
        request.setOutTradeNo(order.getOrderNo());
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        return response.getCodeUrl();
    }

    @Autowired
    public void setWxPayConfig(Config payConfig) {
        this.payConfig = payConfig;
    }

    @Autowired
    public void setWxPayConfig(WxPayConfig wxPayConfig) {
        this.wxPayConfig = wxPayConfig;
    }
}
